package zengweicong.com.performancetest.activity;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zengweicong
 */
public class ThreadUtil {

    /**解决java.util.concurrent.RejectedExecutionException
    https://blog.csdn.net/wzy_1988/article/details/38922449
    见https://blog.csdn.net/iteye_2701/article/details/82100867?utm_source=distribute.pc_relevant.none-task*/
    private static ExecutorService sExecutorService = new ThreadPoolExecutor(
            //线程池核心池大小
            20,
            //线程池最大线程数量
            150,
            //当线程数大于核心时，此为终止前多余的空闲线程等待新任务的最长时间。
            30L,
            //上一个参数的单位
            TimeUnit.MILLISECONDS,
            //用来储存等待执行任务的队列。线程等待队列
            new LinkedBlockingDeque<Runnable>(),
            new ThreadPoolExecutor.CallerRunsPolicy());

    public static void queueRun(Runnable runnable) {
        sExecutorService.execute(runnable);
    }

    public static ExecutorService getExecutorService() {
        return sExecutorService;
    }

    public static ExecutorService newSingleExecutorService() {
        return new ThreadPoolExecutor(
                //线程池核心池大小
                1,
                //线程池最大线程数量
                3,
                //当线程数大于核心时，此为终止前多余的空闲线程等待新任务的最长时间。
                0L,
                //上一个参数的单位
                TimeUnit.MILLISECONDS,
                //用来储存等待执行任务的队列。线程等待队列
                new LinkedBlockingDeque<Runnable>(3),
                new ThreadPoolExecutor.AbortPolicy());
    }
}